

package com.hazelcast.client.impl.protocol.task.dynamicconfig;

import com.hazelcast.config.PredicateConfig;
import com.hazelcast.internal.namespace.NamespaceUtil;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.query.Predicate;

import javax.annotation.Nullable;

/**
 *
 */
public class PredicateConfigHolder {

    private final String className;
    private final String sql;
    private final Data implementation;

    public PredicateConfigHolder(String className, String sql, Data implementation) {
        this.className = className;
        this.sql = sql;
        this.implementation = implementation;
    }

    public static PredicateConfigHolder of(PredicateConfig config, SerializationService serializationService) {
        return new PredicateConfigHolder(config.getClassName(), config.getSql(), serializationService.toData(config.getImplementation()));
    }

    public String getClassName() {
        return className;
    }

    public String getSql() {
        return sql;
    }

    public Data getImplementation() {
        return implementation;
    }

    public PredicateConfig asPredicateConfig(SerializationService serializationService, @Nullable String namespace) {
        if (className != null) {
            return new PredicateConfig(className);
        } else
            if (implementation != null) {
                return NamespaceUtil.callWithNamespace(namespace, () -> {
                    Predicate predicate = serializationService.toObject(implementation);
                    return new PredicateConfig(predicate);
                });
            } else {
                return new PredicateConfig();
            }
    }
}
